<?php

namespace Wap\Controller;

use Think\Controller;
use Think\Model;
use User\Model\FactoryModel;
use Wap\Service\PraiseService;
use Wap\Service\RuleService;
use Wap\Service\WeixinService;
use Wap\Service\CustomerService;

class PraiseeatController extends WapController
{

    public $_praise;//活动信息
    public $wxuser;//活动绑定的微信号
    public $user;//微信用户

    public $secure_actions = array("fetch_one", "upload", "edit");
    public $unsecure_actions = array("index", "introduction", "teacher", "teacherdetail");

    public function __construct()
    {
        parent::__construct();
        $this->handleCriteriaPraise();
        $this->handleCriteriaWxuser();

        $wxJSApi = WeixinService::buildWXJSApi($this->wxuser);
        if (empty($wxJSApi)) {
            header("Content-type: text/html; charset=utf-8");
//            die('服务器繁忙请稍后！');
            /*echo json_encode($this->wxuser);
            echo json_encode($wxJSApi);
            die();*/
        }
        $this->assign('nonceStr', $wxJSApi['noncestr']);
        $this->assign('wxTicket', $wxJSApi['ticket']);
        $this->assign('timestamp', $wxJSApi['timestamp']);
        $this->assign('wxSha1', $wxJSApi['sha1']);

        $this->assign("wxuser", $this->wxuser);
        $this->assign("praise", $this->_praise['id']);//TODO: should be clear
        $this->assign("praiseContent", $this->_praise);//TODO: should be clear
        $this->assign("info", $this->_praise['link']);
        $imgurl = "";
        if (!empty($this->_praise) && !empty($this->_praise['picurl'])) {
            $picArr = explode(";", $this->_praise['picurl']);
            $imgurl = $picArr[0];
        }
        $this->assign("imgurl", $imgurl);//TODO: should be clear

        $share_info = json_decode($this->_praise['info'], true);
        $share_title = $this->_praise['title'];
        $share_desc = $this->_praise['title'] . "，快来为TA添人气吧！";
        $share_pic = $imgurl;
        if (!empty($share_info['share_title'])) {
            $share_title = $share_info['share_title'];
        }
        if (!empty($share_info['share_desc'])) {
            $share_desc = $share_info['share_desc'];
        }
        if (!empty($share_info['share_pic'])) {
            $share_pic = 'http://' . $_SERVER['HTTP_HOST'] . $share_info['share_pic'];
        }
        $this->assign('share_title', $share_title);
        $this->assign('share_desc', $share_desc);
        $this->assign('share_pic', $share_pic);
    }

    /**
     *函数名: index
     *函数描述: 获取微信网页静默授权CODE、加载所有作品主页模板
     * @param string $_GET ['code'];
     * @return object 模板
     */
    public function index()
    {
        if (I('get.type', '', '') != 'info') {
            return $this->display();
        } else {
            return $this->display('info');
        }
    }

    /**
     *函数名: introduction
     *函数描述: 渲染活动介绍模板
     * @return object 模板
     */
    public function introduction()
    {
        $this->display();  //"active"
    }

    public function home()
    {
        //$this->handleCriteriaURL();
        //$this->handleCriteriaUser();
        //$this->handleCriteriaCustomer();

        $user = I("get.user", -1, "");
        $praise = I("get.praise", -1, "");
        $customer_id = CustomerService::getID();
        //usleep( 500 );
        //usleep( 800 );
        $online = CustomerService::check();
        /*if( $customer_id && !$online ){
            header( "Location: ".U( 'Wap/Praise', array( 'praise' => I( 'praise', -1, '' ) ) ) );
        }*/

        if (!$online) {
            $try = session("try.home");
            if ($try === null) {
                session("try.home", 1);
                header("Location: " . U('Wap/praiseeat/home', array('praise' => I('praise', -1, ''))));
                exit();
            } else if ($try < 3 && $try > 0) {
                $try = ($try + 1) % 3;
                session("try.home", $try);
                header("Location: " . U('Wap/praiseeat/home', array('praise' => I('praise', -1, ''))));
                exit();
            } else if ($try === 0) {
                session("try.home", null);
                $this->error("信息异常, 请尝试重新登录", "#");
            }
        }
        session("try.home", null);

        $condition['uid'] = $customer_id;
        $condition['praise_id'] = $praise;
        $datas = D("praise_item")->where($condition)->select();

        $status = PraiseService::access($praise);
        $this->assign("status", $status);
        $this->assign("datas", $datas);
        $this->display();
    }

    /**
     *函数名: fetch_one
     *函数描述: 查看具体某一幅作品信息
     * @param int $_GET ['id'] 作品ID
     * @return object 渲染作品详情页模板、模板赋值
     */
    public function fetch_one()
    { //查看一幅具体作品
//        $this->handleCriteriaURL();
//        $this->handleCriteriaUser();
//        $this->handleCriteriaCustomer();

        $id = I("get.id", -1, "");//TODO: 输入控制
        $praise = I('get.praise', -1, '');

        $condition['esm_praise_item.id'] = $id;

        $datas = D('praiseItem')->fetch_by_id($id);
        $rank = D("praiseItem")->fetch_rank_by_id($datas['id']);
        $check = RuleService::is_good($praise, $this->user['openid'], array('updated_time' => time(), 'praise' => $praise, 'openid' => $this->user['openid'], 'pid' => $id));
        $checked = $check['error'] ? 0 : 1;

        if (!count($datas)) {
            $this->error('该作品不存在、或未被审核通过', '#');
        }
        $cond['status'] = 1;
        switch ($praise){
            case 95:
                $cond['topic_id'] = -10;break;
            case 96:
                $cond['topic_id'] = -12;break;
            case 121:
                $cond['topic_id'] = -13;break;
        }

        $cond['chat_id'] = $id;

        $comments = M("live_comment")->where($cond)->order("id asc")->select();
        $this->assign('comments', $comments);
        $this->assign('openid', $this->user['openid']);
        $this->assign("followLink", "http://" . $_SERVER['HTTP_HOST'] . "/Wap/praiseeat/index/praise/" . $this->_praise['id']);
        $this->assign("rank", $rank);
        $this->assign("result", $datas);
        $this->assign('checked', $checked);
        $this->display();  //原文件名称 photodetail
    }

    public function edit()
    {
        $this->handleCriteriaURL();
        $this->handleCriteriaUser();
        $this->handleCriteriaCustomer();

        $customer_id = CustomerService::getID();
        if (!$customer_id) {
            $this->error("当前用户不在线", "#");//TODO:
        }

        $condition['praise_id'] = I("get.praise", -1, '');
        $condition['id'] = I('get.id', -1, '');
        $condition['status'] = -1;

        // $this->share['link'] = C("SITE_URL").'/'.U('Wap/praiseeat/index', array( 'praise' => $condition['praise'] ) );

        $data = D('praise_item')->where($condition)->find();

        // $this->assign( "share", $this->share );
        $this->assign("customer", $customer_id);
        $this->assign("data", $data);
        $this->display("upload");
    }

    /*
    *是否合法活动
    */
    private function handleCriteriaPraise()
    {
        $this->praise = I("get.praise", -1, "");
//        trace($this->praise,"test:","SQL");
        $result = PraiseService::is_good($this->praise, time());
        $this->_praise = PraiseService::getPraise($this->praise);
        if ($result['good'] === false) {
            $this->error($result['msg'], "#");
        }
    }

    /*
    *静默授权url生成
    */
    private function handleCriteriaURL()
    {
        if (!isset($_GET['code'])) {
            $url = C('SITE_URL') . $_SERVER['REQUEST_URI'];
            $url = WeixinService::buildOauthURI($url, $this->wxuser['appid']);
            header("Location: " . $url);
            exit();
        } else {
//            trace( $_SERVER, "server", "SQL" );
        }
    }

    /*
    *微信公众号信息
    */
    private function handleCriteriaWxuser()
    {
        $this->wxuser = WeixinService::getWxuser($this->_praise['token']);
    }

    /*
    *微信用户
    */
    private function handleCriteriaUser()
    {
        /*if(isset($_GET['code'])){
            WeixinService::setUser( $this->wxuser['appid'], $this->wxuser['appsecret'], $_GET['code'] );
            $this->user = WeixinService::getUser();
            //trace( $this->user, "微信用户信息", "INFO" );
            //usleep( 800 );
            //S( "debug_user", $this->user, 3600 );//todo: exception for index
            //$this->user = S( "debug_user" );
        }*/

        $this->user = WeixinService::getUser();
        if (isset($_GET['code']) && !$this->user) {
            WeixinService::setUser($this->wxuser['appid'], $this->wxuser['appsecret'], $_GET['code']);
            $this->user = WeixinService::getUser();
            //trace( $this->user, "微信用户信息", "INFO" );
            //usleep( 800 );
            //S( "debug_user", $this->user, 3600 );//todo: exception for index
            //$this->user = S( "debug_user" );
        }
    }

    /*
    *注册用户
    */
    private function handleCriteriaCustomer()
    {
        CustomerService::setOpenID($this->user['openid']);
    }

    //--管理员登录界面--
    public function manage()
    {
        $praise_id = $this->_praise['id'];
        $cond['topic_id'] = -$praise_id;
        $cond['status'] = array("NEQ", -1);
        $page = I('get.page', 0, '');
        $items = M("live_comment")->where($cond)->order('id desc')->limit(0, 10)->select();
        $this->assign("items", $items);
        $this->display();
    }

    public function comment_more()
    {
        $praise_id = $this->_praise['id'];
        $cond['topic_id'] = -$praise_id;
        $cond['status'] = array("NEQ", -1);
        $page = I('get.page', 0, '');
        $items = M("live_comment")->where($cond)->order('id desc')->limit($page * 10, 10)->select();
        $this->ajaxReturn(array("items" => $items));
    }

    public function item_more()
    {
        $cond['praise_id'] = I("get.praise", -1, '');
        $cond['status'] = array("NEQ", -1);
        $page = I('get.page', 0, '');
        $items = M("praise_item")->where($cond)->order('id desc')->limit($page * 10, 10)->select();
        $this->ajaxReturn(array("items" => $items));
    }

    public function item_pass()
    {
        $cond['id'] = I("get.itemId", -1, '');
        if (!empty($cond['id'])) {
            $data['status'] = 1;
            M("praise_item")->where($cond)->save($data);
        }
    }

    public function item_delete()
    {
        $cond['id'] = I("get.itemId", -1, '');
        if (!empty($cond['id'])) {
            $data['status'] = -1;
            M("praise_item")->where($cond)->save($data);
        }
    }

    public function comment_pass()
    {
        $cond['id'] = I("get.id", -1, '');
        if (!empty($cond['id'])) {
            $data['status'] = 1;
            M("live_comment")->where($cond)->save($data);

            $item_id = I("get.item", -1, "");
            $praise_item = M("praise_item")->where(['id' => $item_id])->find();
            $data_item['share'] = $praise_item['share'] + 5;
            M("praise_item")->where(['id' => $item_id])->save($data_item);
        }
    }

    public function comment_delete()
    {
        $cond['id'] = I("get.id", -1, '');
        if (!empty($cond['id'])) {
            $data['status'] = -1;
            M("live_comment")->where($cond)->save($data);
        }
    }

    public function comment_add()
    {
        $data['chat_id'] = I("post.item_id", -1, '');
        $data['content'] = I("post.comment", '', '');
        $praise_id = $this->_praise['id'];
        $data['topic_id'] = -$praise_id;
        $data['status'] = 0;
        $id = M("live_comment")->add($data);
        $this->ajaxReturn($id);
    }

    public function item_add()
    {
        $data['status'] = 9;
        $data['show_name'] = I("post.name", '', '');
        if (empty($data['show_name'])) {
            $data['show_name'] = '发现花园之美，为家乡点赞';
        }
        $data['praise_id'] = I("post.praise", -1, '');
        $img_data = I("post.pic", '', '');
        $ajaxImg = FactoryModel::ajaxImgUploadThumb($img_data, "praiseeat");
        $max_id = M("praise_item")
            ->field("max(grade) as grade")
            ->where(['praise_id' => $data['praise_id']])
            ->find();
        if (empty($max_id['grade'])) {
            $data['grade'] = 1;
        } else {
            $data['grade'] = $max_id['grade'] + 1;
        }
        if ($ajaxImg['code'] == -1) {
            $this->ajaxReturn("上传图片失败");
        } else {
            $data['pic'] = $ajaxImg['msg'];
        }
        $id = M("praise_item")->add($data);
        $this->ajaxReturn($id);
    }

    public function update_item_connect()
    {
        $cond["id"] = I("post.id", -1, '');
        $data['parent_telephone'] = I("post.telephone", "", '');
        M("praise_item")->where($cond)->save($data);
        $this->ajaxReturn(1);
    }

    public function update_item_comment()
    {
        $cond["id"] = I("post.id", -1, '');
        $data['reserve'] = I("post.telephone", "", '');
        M("live_comment")->where($cond)->save($data);
        $this->ajaxReturn(1);
    }
}
